package com.kx.base.controller;

import com.kx.base.util.JWTUtil;
import com.kx.base.vo.UserVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * controller的标准定义
 * 集成各种公共方法
 * @Author Sun
 * @Date 2021/7/17 19:29
 */
public class BaseController {

    /**
     * 获取当前线程绑定的request方法
     */
    public static HttpServletRequest request(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取当前线程绑定的request方法
     */
    public static HttpServletResponse response(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

    /**
     * 获取当前登录的用户实体
     */
    public static UserVO user(){
        String token = request().getHeader("token");
        //解析token
        UserVO userVO = JWTUtil.checkToken(token);
        return userVO;
    }

    /**
     * 获取当前登录用户的id
     */
    public Long userId(){
        UserVO user = user();
        return user == null ? null : user.getId();
    }
}
